<template>
  <div class="dataModel">
    <div class="left" style="padding: 10px">
      <customTree :ancestralId="listQuery.ancestralId" :btnTitle="'  新建目录  '" @getId="getId" :type="true"
        @getTree="getTree" :expandType="'1'" />
    </div>

    <div class="right">
      <el-row>
        <el-col :span="24" style="color: blue">核心数据模型</el-col>
      </el-row>
      <el-row>
        <el-col :span="4">
          <!-- <span style="border-left: 2px solid blue; font-size: 20px">&nbsp;&nbsp;&nbsp;核心数据模型管理</span> -->
          <span>&nbsp;&nbsp;&nbsp;</span>
        </el-col>
        <el-col :span="20">
          <div style="display: flex; flex-direction: row; justify-content: flex-end">
            <el-dropdown style="margin-right: 20px">
              <el-button type="primary" @click="handleClick('add')"><i class="el-icon-plus"></i> 在线填报</el-button>
              <el-dropdown-menu> </el-dropdown-menu>
            </el-dropdown>
            <template v-if="activeindex != 0">

              <el-dropdown style="margin-right: 20px">
                <el-button type="success" @click="show = true"><i class="el-icon-download"></i> 导入文件</el-button>
                <el-dropdown-menu> </el-dropdown-menu>
              </el-dropdown>
              <!-- <el-badge :value="activeindex" class="item">
                <el-button type="primary" @click="updataClick(0)"><i class="el-icon-upload"></i> 发布</el-button>
              </el-badge> -->
              <!-- <el-badge :value="activeindex" class="item">
                <el-button type="primary" @click="updataClick(1)"><i class="el-icon-upload" style="transform: rotate(180deg)"></i> 废止 </el-button>
              </el-badge> -->
              <el-badge :value="activeindex" class="item">
                <el-button type="info" @click="exportClick"><i class="el-icon-download"></i> 下载数据模型</el-button>
              </el-badge>
              <el-badge :value="activeindex" class="item">
                <el-button type="danger" @click="delclick"><i class="el-icon-delete-solid"></i> 删除</el-button>
              </el-badge>
            </template>
            <template v-else>

              <el-dropdown style="margin-right: 20px">
                <el-button type="success" @click="show = true"><i class="el-icon-download"></i> 导入文件</el-button>
                <el-dropdown-menu> </el-dropdown-menu>
              </el-dropdown>
              <el-button type="info" @click="downlowd"><i class="el-icon-download"></i> 下载模板</el-button>
              <!-- <el-button type="primary" @click="updataClick(0)"><i class="el-icon-upload"></i> 发布</el-button> -->
              <!-- <el-button type="primary" @click="updataClick(1)"><i class="el-icon-upload" style="transform: rotate(180deg)"></i> 废止 </el-button> -->
              <el-button type="info" @click="exportClick"><i class="el-icon-download"></i> 下载数据模型</el-button>
              <el-button type="danger" @click="delclick"><i class="el-icon-delete-solid"></i> 删除</el-button>
            </template>
          </div>
        </el-col>
      </el-row>
      <el-row style="display: flex; flex-direction: row; flex-wrap: wrap">
        <el-col :span="3">
          <el-select v-model="optionsArr.releaseStatus" clearable placeholder="请选择发布状态">
            <el-option v-for="item in statusoptions" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-col>
        <!--        <el-col :span="3" :offset="1">-->
        <!--          <el-select v-model="optionsArr.entity" placeholder="请选择实体对象">-->
        <!--            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>-->
        <!--          </el-select>-->
        <!--        </el-col>-->
        <el-col :span="4" :offset="1">
          <el-cascader v-model="optionsArr.elementType" placeholder="请选择数据类型" :options="elementTypeoptions"
            :props="{ checkStrictly: true }" clearable></el-cascader>
        </el-col>
        <el-col :span="4" :offset="1">
          <el-cascader v-model="optionsArr.modelType" placeholder="请选择模型类型" :options="modelTypeoptions"
            :props="{ checkStrictly: true }" clearable></el-cascader>
        </el-col>
        <el-col :span="4" :offset="1">
          <el-select v-model="optionsArr.applyStatus" clearable placeholder="请选择审核状态">
            <el-option-group v-for="group in applyoptions" :key="group.label" :label="group.label">
              <el-option v-for="item in group.options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-option-group>
          </el-select>
        </el-col>
        <el-col :span="4" :offset="1">
          <el-input placeholder="请输入名称" v-model="optionsArr.tableComment" class="input-with-select"> </el-input>
        </el-col>
        <el-col :span="6" style="margin-top: 10px">
          <el-button type="primary" icon="el-icon-search" @click="primaryClick">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="root">重置</el-button>
        </el-col>
      </el-row>

      <el-table ref="table" :data="tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="英文名称" align="center" min-width="100px">
          <template slot-scope="{ row }">
            <span style="cursor: pointer; color: blue" @click="lookvalueFun(row)">{{ row.tableName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="中文名称" align="center" min-width="150px">
          <template slot-scope="{ row }">
            <span style="cursor: pointer; color: blue" @click="lookvalueFun(row)">{{ row.tableComment }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数据类型" align="center" min-width="100px">
          <template slot-scope="{ row }">
            <span>{{ row.elementType }}</span>
          </template>
        </el-table-column>
        <el-table-column label="模型类型" align="center" min-width="100px">
          <template slot-scope="{ row }">
            <span>{{ row.modelType }}</span>
          </template>
        </el-table-column>
        <el-table-column label="模型状态" align="center" min-width="100px">
          <template slot-scope="{ row }">
            <span v-if="row.releaseStatus !== 'null'"
              style="display: inline-block; width: 60px; height: 30px; line-height: 28px; border: 1px solid greenyellow; color: green">{{
                offoron(statusoptions, row.releaseStatus)
              }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" min-width="100px">
          <template slot-scope="{ row }">
            <span style="color: green">{{ getodd(row.applyStatus) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="生效时间" align="center" min-width="130px">
          <template slot-scope="{ row }">
            <span>
              {{ $moment(new Date(row.effectiveStartTime * 1000)).format('YYYY-MM-DD') }}
              ~
              <span v-if="row.effectiveEndTime != '无期限'">
                {{ $moment(new Date(row.effectiveEndTime * 1000)).format('YYYY-MM-DD') }}
              </span>
              <span v-else> 永久 </span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="300px" class-name="small-padding fixed-width">
          <template slot-scope="{ row }">
            <el-button v-if="row.applyStatus !== 'APPROVE_ONLINE_PASS'" type="text" size="small" class="edit-text-btn"
              @click="handle(row)">申请</el-button>
            <el-button type="text" size="small" @click="editvalueFun(row)"> 编辑 </el-button>
            <el-button type="text" size="small" @click="lookvalueFun(row)"> 详情 </el-button>
            <el-button type="text" size="small" class="edit-text-btn" @click="copyvalueFun(row)"> 复制 </el-button>
            <el-button type="text" size="small" class="edit-text-btn" @click="updataClick(row, '0')"> 提交发布 </el-button>
            <el-button type="text" size="small" class="edit-text-btn" @click="updataClick(row, '1')"> 废止 </el-button>
            <el-button type="text" size="small" class="edit-text-btn" @click="updataClick(row, '2')"> 草稿 </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
        :page-sizes="pageArray" @pagination="getList(listQuery)" />

      <modelFrom ref="from" @resList="getList"></modelFrom>
    </div>
    <masterdata-table-form ref="form" @refreshList="getList" />
    <dialogVisibleview ref="addform" :dialogVisible="dialogVisible" :index="index" :eitdValue="eitdValue"
      @dologdin="dologdin" :treeList="treeList" />

    <bindData ref="listData" @getList="getList" />
    <div class="lookzzc" v-if="isboollook">
      <marketLookview :lookobj="lookobj" @offFunValue="offFunValue" :list="list" :treeList="treeList" />
    </div>
    <importView v-if="show" :tree_list="treeList" @change="change" :directoryId="this.listQuery.directoryId" />
  </div>
</template>
<script>
import importView from './importView.vue'
import { deleteableLise, meunsData, tableLise, updatetableLise, detailtableLise, treeListApi, geusen, downloadtable } from '@/api/masterdata/dataModelApi'
import dialogVisibleview from './dialogVisible.vue'
import modelFrom from '@/views/model/datamodel/datamodelFrom.vue'
import Pagination from '@/components/Pagination/index.vue'
import { fetchMedoleList } from '@/api/model/datamodel'
import bindData from '@/views/masterdata/bindData.vue'

import customTree from '@/components/customTree/index.vue'
import { addoneMetaModel } from '@/api/metadata/column'
import { deleteMasterdataDirectory, fetchMasterdataDirectoryList } from '@/api/masterdata/masterdataDirectory'
import { fetchMasterdataTableList } from '@/api/masterdata/masterdataTablelist'
import masterdataTableForm from '@/views/masterdata/masterdataTableForm.vue'
import marketLookview from './marketLookview.vue'
import dayjs from 'dayjs'
export default {
  components: {
    masterdataTableForm,
    customTree,
    bindData,
    Pagination,
    modelFrom,
    dialogVisibleview,
    marketLookview,
    importView,
  },
  computed: {
    getodd: function () {
      return (value) => {
        return this.esdasFun(value)
      }
    },
  },
  data() {
    return {
      show: false,
      index: '',
      list: [],
      lookobj: {},
      loading: false,
      isboollook: false,
      elementTypeoptions: [
        {
          value: '监测数据',
          label: '监测数据',
        },
        {
          value: '普通数据',
          label: '普通数据',
        },
        {
          value: '多媒体数据',
          label: '多媒体数据',
        },
        {
          value: '空间数据',
          label: '空间数据',
          children: [
            {
              value: '影响数据',
              label: '影响数据',
            },
            {
              value: '三维数据',
              label: '三维数据',
            },
            {
              value: '矢量数据',
              label: '矢量数据',
            },
          ],
        },
      ],
      typeoptions: [
        {
          value: '监测数据',
          label: '监测数据',
        },
        {
          value: '普通数据',
          label: '普通数据',
        },
        {
          value: '多媒体数据',
          label: '多媒体数据',
        },
        {
          value: '空间数据',
          label: '空间数据',
          children: [
            {
              value: '影响数据',
              label: '影响数据',
            },
            {
              value: '三维数据',
              label: '三维数据',
            },
            {
              value: '矢量数据',
              label: '矢量数据',
            },
          ],
        },
      ],
      optionsArr: {
        tableComment: undefined,
        releaseStatus: undefined,
        applyStatus: undefined,
        elementType: [],

        modelType: [],
      },
      applyoptions: [
        {
          label: '发布',
          options: [
            {
              value: 'APPROVE_ONLINE_IN_PROGRESS',
              label: '待审核（发布）',
            },
            {
              value: 'APPROVE_ONLINE_PASS',
              label: '审核通过（发布）',
            },
            {
              value: 'APPROVE_ONLINE_REFUSE',
              label: '审核失败（发布）',
            },
          ],
        },
        {
          label: '废止',
          options: [
            {
              value: 'APPROVE_OFFLINE_IN_PROGRESS',
              label: '待审核（废止）',
            },
            {
              value: ' APPROVE_OFFLINE_IN_PASS',
              label: '审核通过（废止）',
            },
            {
              value: 'APPROVE_OFFLINE_IN_REFUSE',
              label: '审核失败（废止）',
            },
          ],
        },
      ],
      statusoptions: [
        { label: '已发布', value: '0' },
        { label: '废止', value: '1' },
        { label: '草稿', value: '2' },
      ],
      filterText: '',
      total: 0,
      NODE_KEY: 'id', // id对应字段
      activeindex: 0,
      options: [],
      activearr: [],
      value: '',
      listQuery: {
        tableName: undefined,
        page: 1,
        limit: this.$store.getters.defaultPageSize,
        ancestralId: '8',
        type: '1',
      },
      tableKey: 0,
      listLoading: true, // 是否加载
      // 添加弹框
      dialogVisible: false,
      // 分页
      currentPage4: 30,
      pageArray: this.$store.getters.pageArray,
      //表格
      tableData: [],
      //侧边层级
      treeList: [],
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      eitdValue: {},
      initParam: {
        // 新增参数
        name: '新增节点',
        parentId: 0,

        children: [],
      },
      updataArr: [],
      MAX_LEVEL: 5, // 设定最大层级
      currentNodekey: '',
      startId: null,
      NODE_ID_START: 0, // 新增节点id，逐次递减
      title: '',
      size: '',
      modelTypeoptions: [
        {
          value: '字典表',
          label: '字典表',
        },
        {
          value: '关联表',
          label: '关联表',
          children: [
            {
              value: '业务数据表',
              label: '业务数据表',
            },
            {
              value: '基础数据表',
              label: '基础数据表',
            },
          ],
        },
      ],
    }
  },

  created() {
    if (this.$route.query.id !== undefined) {
      this.lookvalueFun(this.$route.query)
    }
  },

  methods: {
    getId(data) {

      this.listQuery.ancestralId = '8'
      this.listQuery.directoryId = data.id
      this.getList(this.listQuery)
    },
    getTree(data) {
      this.treeList = data
    },

    downlowd() {
      this.download('/system/metadataModel/table/download', {}, 'post', `${'核心数据模型模版' + new Date().toLocaleDateString() + ' ' + new Date().toLocaleTimeString()}.xlsx`)
    },
    handle(item) {
      geusen({
        type: 0,
        dataId: item.id,
      }).then((res) => {
        if (res.data.code == 0) {
          this.$message.success(res.data.msg)
          this.getList(this.listQuery)
        }
      })
    },
    change() {
      this.show = false
      this.getList(this.listQuery)
    },
    offoron(item, value) {
      let list = ''
      item.map((v, i) => {
        if (v.value == value) {
          list = v.label
        }
      })
      return list
    },
    esdasFun(value) {
      let list = ''
      this.applyoptions.map((v, i) => {
        v.options.map((val, index) => {
          if (val.value == value) {
            list = val.label
          }
        })
      })
      return list
    },
    updataClick(item, index) {
      item.releaseStatus = index
      updatetableLise({
        ...item,
        id: item.id,
        releaseStatus: item.releaseStatus,
      }).then((res) => {
        this.getList(this.listQuery)
      })
    },

    offFunValue() {
      this.isboollook = false
    },
    exportClick() {
      if (this.activearr.length) {
        this.download('/system/metadataModel/table/export', { ids: this.activearr }, 'post', `核心数据模型 ${dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')}.xlsx`)
      } else {
        this.$message({
          type: 'error',
          message: '请选择数据',
        })
      }
    },
    copyvalueFun(item) {
      detailtableLise({
        params: {
          id: item.id,
        },
      }).then((res) => {
        if (res.data.code == 200) {
          this.eitdValue = res.data.data
          this.index = 'copy'
          this.dialogVisible = true
        }
      })
    },
    editvalueFun(item) {
      detailtableLise({
        params: {
          id: item.id,
        },
      }).then((res) => {
        this.eitdValue = res.data.data
        this.index = 'edit'
        this.dialogVisible = true
      })
    },
    delclick() {
      if (this.activearr.length) {
        deleteableLise({ ids: this.activearr }).then((res) => {
          if (res.data.code == 0) {
            this.$message({
              message: res.data.msg,
              type: 'success',
            })
            let obj = {
              tableComment: this.optionsArr.tableComment,
              releaseStatus: this.optionsArr.releaseStatus,
              applyStatus: this.optionsArr.applyStatus,
              elementType: this.optionsArr.elementType.length ? this.optionsArr.elementType.join('/') : [],
              modelType: this.optionsArr.modelType.length ? this.optionsArr.modelType.join('/') : [],
            }
            this.getList({ ...this.listQuery, ...obj })
          } else {
            this.$message(res.data.msg)
          }
        })
      } else {
        this.$message({
          type: 'error',
          message: '请选择数据',
        })
      }
    },
    lookvalueFun(item) {
      detailtableLise({
        params: {
          id: item.id,
        },
      }).then((res) => {
        this.lookobj = res.data.data
      })
      this.isboollook = true
    },
    root() {
      this.optionsArr = {
        tableComment: undefined,
        releaseStatus: undefined,
        applyStatus: undefined,
        elementType: [],
        modelType: [],
      }
      this.listQuery = {
        directoryId: this.listQuery.directoryId,
        page: this.listQuery.page,
        limit: this.$store.getters.defaultPageSize,
      }
      this.getList(this.listQuery)
    },
    primaryClick() {
      let obj = {
        tableComment: this.optionsArr.tableComment,
        releaseStatus: this.optionsArr.releaseStatus,
        entity: this.optionsArr.entity,
        applyStatus: this.optionsArr.applyStatus,
        elementType: this.optionsArr.elementType.length ? this.optionsArr.elementType.join('/') : [],
        modelType: this.optionsArr.modelType.length ? this.optionsArr.modelType.join('/') : [],
      }
      this.getList({ ...this.listQuery, ...obj })
    },
    dologdin(item) {
      this.dialogVisible = item
      this.getList({ ...this.listQuery })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },

    getList(item) {
      this.loading = true
      fetchMasterdataTableList(item).then((response) => {
        this.tableData = response.data.data.records
        this.total = response.data.data.total
        this.loading = false
      })
    },

    // 多选
    handleSelectionChange(value) {
      let ids = []
      value.map((v, i) => {
        // ids.push(v.id.replace(/\"/g, ""))
        ids.push(v.id)
      })

      this.updataArr = value
      this.activearr = ids.join().replace(/[\[\]]/g, '')
      this.activeindex = value.length
    },

    handleDeletetree(_node, _data) {
      // 删除节点

      console.log(_node, _data)
      // 判断是否存在子节点
      if (_data.children && _data.children.length !== 0) {
        this.$message.error('此节点有子级，不可删除！')
        return false
      } else {
        // 删除操作
        let DeletOprate = () => {
          this.$nextTick(() => {
            if (this.$refs.SlotTree) {
              deleteMasterdataDirectory(_data.id).then((res) => {
                this.$message.success('删除成功！')
                this.$refs.SlotTree.remove(_data)
              })
            }
          })
        }

        // 二次确认
        let ConfirmFun = () => {
          this.$confirm('是否删除此节点？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              DeletOprate()
            })
            .catch(() => { })
        }

        // 判断是否新增： 新增节点直接删除，已存在的节点要二次确认
        _data[this.NODE_KEY] < this.NODE_ID_START ? DeletOprate() : ConfirmFun()
      }
    },
    handleClick(item) {
      this.index = item
      this.dialogVisible = true
      this.$refs.addform.root()
    },

    //分页事件
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
    },
  },
}
</script>
<style lang="scss" scoped>
.el-cascader,
.el-input,
.el-select {
  width: 100% !important;
}

.item {
  margin-right: 20px;
}

.lookzzc {
  position: absolute;
  right: 11px;
  top: 0.625rem;
  width: 99%;
  height: 95vh;
  z-index: 4;
}

.zzc {
  width: 80%;
  height: 100%;
  margin: 0 auto;
}

.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.dataModel {
  width: 100%;
  height: 100%;
  display: flex;
  position: relative;
  overflow: hidden;

  .left {
    width: 22%;
    background-color: white;
    border-right: 1px solid rgb(223, 230, 236);

    .l-one {
      width: 100%;
      height: 6vh;
      box-sizing: border-box;
      display: flex;
      list-style: none;
      flex-direction: row;
      align-items: center;
      justify-content: space-evenly;

      span {
        width: 50%;
        height: 100%;
        line-height: 6vh;
      }
    }

    .l-tow {
      width: 100%;
      height: 4vh;
      border-radius: 2px;

      input {
        width: 90%;
        height: 100%;
        outline: 0;
        border: none;
        border-radius: 2px 0px 0px 2px;
      }

      i {
        width: 10%;
        height: 100%;

        text-align: center;
      }
    }

    .l-three {
      width: 100%;
      height: 90vh;
    }
  }

  .right {
    width: 78%;
    margin: 10px;
    padding: 10px;
    background-color: white;
    overflow: auto;

    .el-table {
      width: 100%;
    }
  }
}

.btn {
  width: 100%;
}
</style>
